const SEQUENCE_MODE = 1//列表循环
const RANDOM_MOD = 2//随机循环
const SINGLE_CYCLE_MOD = 3 // 单曲循环

const app = getApp();
const SongData={
  play:'play',
  currentTime:0,
  duration:0,
  percent:0
}

function randomNum(minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10);
      break;
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
      break;
    default:
      return 0;
      break;
  }
}

function getNextIndex(nextFlag,len) {
  let ret,
      currentIndex = app.globalData.currentIndex,
      mod = app.globalData.playMod
  if (mod === RANDOM_MOD) {
    ret = randomNum(len)
  } else {
    if (nextFlag) {
      ret = currentIndex + 1 == len ? 0 : currentIndex + 1
    } else {
      ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
    }
  }
  return ret
}

function togglePlaying() {
  wx.getBackgroundAudioPlayerState({
    success: function (res) {
      var status = res.status
      if (status == 1) {
        wx.pauseBackgroundAudio()
      } else {
        wx.playBackgroundAudio()
      }
    }
  })
}

function changeMod() {
  let playMod = app.globalData.playMod + 1
  if (playMod > SINGLE_CYCLE_MOD) {
    playMod = SEQUENCE_MODE
  }
  return playMod
}

function _pad(num, n = 2) {
  let len = num.toString().length
  while (len < n) {
    num = '0' + num
    len++
  }
  return num
}

function _formatTime(interval) {
  interval = interval | 0
  const minute = interval / 60 | 0
  const second = _pad(interval % 60)
  return `${minute}:${second}`
}

// 去掉歌词中的转义字符
function _normalizeLyric(lyric) {
  return lyric.replace(/&#58;/g, ':').replace(/&#10;/g, '\n').replace(/&#46;/g, '.').replace(/&#32;/g, ' ').replace(/&#45;/g, '-').replace(/&#40;/g, '(').replace(/&#41;/g, ')')
}
// 歌词滚动回调函数
function handleLyric(currentTime) {
  // let lines = [{time: 0, txt: ''}], lyric = this.data.currentLyric, lineNum
  // lines = lines.concat(lyric.lines)
  // for (let i = 0; i < lines.length; i++) {
  //   if (i < lines.length - 1) {
  //     let time1 = lines[i].time, time2 = lines[i + 1].time
  //     if (currentTime > time1 && currentTime < time2) {
  //       lineNum = i - 1
  //       break;
  //     }
  //   } else {
  //     lineNum = lines.length - 2
  //   }
  // }
  // this.setData({
  //   currentLineNum: lineNum,
  //   currentText: lines[lineNum + 1] && lines[lineNum + 1].txt
  // })

  // let toLineNum = lineNum - 5
  // if (lineNum > 5 && toLineNum != this.data.toLineNum) {
  //   this.setData({
  //     toLineNum: toLineNum
  //   })
  // }
}
// 获取歌词
function _getLyric(currentSong) {
    // if (currentSong.words == 0) {
    //   const lyric = this._normalizeLyric(currentSong.words)
    //   this.setData({
    //     currentLyric: lyric
    //   })
    // } else {
    //   this.setData({
    //     currentLyric: null,
    //     currentText: ''
    //   })
    // }
}
function _formatSecod(time) {
  time = time || 0
  var min = time.split(':')[0];
  var sec = time.split(':')[1];
  var s = Number(min*60) + Number(sec);
  return s
}

// 滑动
function musicchange(e,max,duration){
  var current=Number(e.detail.value);
  var duration=_formatSecod(duration) || 0;
  var change='';
  change=current/max*duration;
  onTimeUpdate(change)
}
function onTimeUpdate(time){
  // 监听播放拿取播放进度
  const manage = wx.getBackgroundAudioManager()
  if(time){
    manage.seek(time);
  }
  manage.onTimeUpdate(() => {
    const currentTime = manage.currentTime;
    const duration=manage.duration
    SongData.currentTime=_formatTime(currentTime)
    SongData.duration=_formatTime(duration)
    SongData.percent=currentTime / duration*100
    
    if(app.globalData.currentLyric) {
      handleLyric(currentTime * 1000)
    }
    
  })
}
// 创建播放器
function _createAudio(currentSong) {
  wx.playBackgroundAudio({
    dataUrl: currentSong.audioUrl,
    title: currentSong.title,
    coverImgUrl: currentSong.imgUrl
  })
  // 监听音乐播放。
  wx.onBackgroundAudioPlay(() => {
    SongData.play='play'
    app.play(currentSong.id)
  })
  // 监听音乐暂停。
  wx.onBackgroundAudioPause(() => {
    SongData.play='pause'
  })
  // 监听音乐停止。
  wx.onBackgroundAudioStop(() => {
    if(app.globalData.closetimeend){
      return
    }
    if (app.globalData.playMod === SINGLE_CYCLE_MOD) {
      SongData.play='end'
    }
    next()
  })
  onTimeUpdate()
}
// 获取播放地址
function _getPlayUrl(currentSong) {
  if (currentSong.audioUrl) {
    _createAudio(currentSong)
    return SongData
  } else {
    wx.showToast({
      title: '本歌曲暂时不能播放。请切换下一首',
      icon: 'none'
    })
  }
}
function prev() {
  app.globalData.currentIndex = getNextIndex(false)
}
function next() {
  app.globalData.currentIndex = getNextIndex(true)
}

module.exports = {
  prev,
  next,
  getPlayUrl:_getPlayUrl,
  createAudio:_createAudio,
  musicchange,
  formatTime:_formatTime,
  togglePlaying,
  changeMod,
  getLyric:_getLyric
}